package runnable;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @classname:Money
 * @description:
 * @author: Mr.Z
 * @date: 2020/12/19 15:34
 * @version: 0.1
 * @since:1.8
 */
public class Money {
    private static Integer balance = 1000;

    private final ReentrantLock lock = new ReentrantLock();
    public void saveMoney(int money){
        lock.lock();
        try {
            balance+=money;
            System.out.println(Thread.currentThread().getName()+"转账给我"+money+"块钱，账号余额"+balance);
        } finally {
            lock.unlock();
        }

    }

    public void drawMoney(int money){
        lock.lock();
        try {
            balance-=money;
            System.out.println("我给"+Thread.currentThread().getName()+"转账"+money+"元,账号余额"+balance);
        } finally {
            lock.unlock();
        }


    }


    //同步代码快
    /*public void saveMoney(int money){
        synchronized ("a") {
            balance+=money;
            System.out.println(Thread.currentThread().getName()+"转账给我"+money+"块钱，账号余额"+balance);
        }
    }

    public void drawMoney(int money){
        synchronized ("a") {
            balance-=money;
            System.out.println("我给"+Thread.currentThread().getName()+"转账"+money+"元,账号余额"+balance);
        }
    }*/



   /* public void saveMoney(int money){
        synchronized ("a") {
            balance+=money;
            System.out.println(Thread.currentThread().getName()+"转账给我"+money+"块钱，账号余额"+balance);
        }
    }

    public void drawMoney(int money){
        synchronized ("a") {
            balance-=money;
            System.out.println("我给"+Thread.currentThread().getName()+"转账"+money+"元,账号余额"+balance);
        }
    }*/
/*
     public static synchronized void saveMoney(int money){
             balance+=money;
             System.out.println(Thread.currentThread().getName()+"转账给我"+money+"块钱，账号余额"+balance);
     }

     public static synchronized void drawMoney(int money){
             balance-=money;
             System.out.println("我给"+Thread.currentThread().getName()+"转账"+money+"元,账号余额"+balance);
     }*/


    public Integer getBalance() {
        return balance;
    }

}
